$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/user/list',
        datatype: "json",
        colModel: [			
			{ label: '用户ID', name: 'userId', index: "user_id", width: 45, key: true, hidden:true},
			{ label: '用户名', name: 'username', width: 75 },
            { label: '昵称', name: 'nickName', width: 75 },
            { label: '所属部门', name: 'deptName', width: 75 },
			{ label: '邮箱', name: 'email', width: 90 },
			{ label: '手机号', name: 'mobile', width: 50 },
			{ label: '状态', name: 'status', width: 20, formatter: function(value, options, row){
				return value === 0 ? 
					'<span class="label label-danger">禁用</span>' : 
					'<span class="label label-success">正常</span>';
			}},
			{ label: '创建时间', name: 'createTime', index: "create_time", width: 60},
            { label: '最后登录时间', name: 'lastLoginTime', index: "last_login_time", width: 60}
        ],
		viewrecords: true,
        height: 365,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });

    var href = window.location.href;
    if ( href.indexOf("?xh=") != -1 ) {
        var xh = href.substring(href.indexOf("?xh=")+4,href.length);
        vm.showList = false;
        vm.user.username = xh;
        vm.nameDisabled = true;
    }
   ;
});
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    }
};
var ztree;

var vm = new Vue({
    el:'#rrapp',
    data:{
        q:{
            username: null
        },
        showList: true,
        title:null,
        roleList:{},
//        courseList:{},
        nameDisabled:false,
        user:{
            status:1,
            deptId:null,
            deptName:null,
            roleIdList:[],
//            courseIdList:[],
            deptIdList:[]
        }
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function(){
            vm.showList = false;
            vm.title = "新增";
            vm.roleList = {};
//            vm.courseList = {};
            vm.user = {deptName:null, deptId:null, status:1, roleIdList:[]/*,courseIdList:[]*/,deptIdList:[]};

            //获取角色信息
            this.getRoleList();
            
            //获取课程信息
//            this.getCourseList();

            vm.getDept();
        },
        getDept: function(){
            //加载部门树
            $.get(baseURL + "sys/dept/list", function(r){
                ztree = $.fn.zTree.init($("#deptTree"), setting, r);
                var node = ztree.getNodeByParam("deptId", vm.user.deptId);
                if(node != null){
                    ztree.selectNode(node);

                    vm.user.deptName = node.name;
                }
            })
        },
        update: function () {
            var userId = getSelectedRow();
            if(userId == null){
                return ;
            }

            vm.showList = false;
            vm.title = "修改";

            vm.getUser(userId);
            //获取角色信息
            this.getRoleList();
            
            //获取课程信息
//            this.getCourseList();
        },
        del: function () {
            var userIds = getSelectedRows();
            if(userIds == null){
                return ;
            }

            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "sys/user/delete",
                    contentType: "application/json",
                    data: JSON.stringify(userIds),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        saveOrUpdate: function () {
            var url = vm.user.userId == null ? "sys/user/save" : "sys/user/update";
//            console.log(vm.user);
            
//            console.log(vm.courseList);//全部课程
//        	console.log(vm.user.courseIdList);//已选课程id
        	
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.user),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(){
/*
//                        	console.log(vm.user.roleIdList);
//                        	console.log(vm.user.courseIdList);
                        	//保存选课数据↓
                        	var courseEditData = new Object();
                        	courseEditData.xh = vm.user.username ;
                        	
                            $.get(baseURL + "jyxskc/bathDeleteByXh/"+courseEditData.xh, function(r){
//                                console.log(r);
//                                console.log(courseEditData.xh+"重置选课");
                            });
                        	
                        	for(var i = 0 ; i < vm.courseList.length ; ++i){//遍历全部课程
                        		courseEditData.kcid = vm.courseList[i].id ;
//                        		console.log(courseEditData.kcid);
                        		if(in_array(vm.courseList[i].id ,vm.user.courseIdList)){//课程是已选课程
                        			courseEditData.deleteState = 0 ;//保存
                                    $.ajax({
                                        type: "POST",
                                        url: baseURL + "jyxskc/save",
                                        contentType: "application/json",
                                        data: JSON.stringify(courseEditData),
                                        success: function(r){
//                                        	console.log(r);
                                            if(r.code === 0){
                                            	console.log("课程"+courseEditData.kcid+"状态"+courseEditData.deleteState);
                                            }else{
                                            	console.log("课程保存出错");
                                            }
                                        }
                                    });        		
                        		}
                        		
                        	}                        	
                        	//保存选课数据↑
*/
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        getUser: function(userId){
            $.get(baseURL + "sys/user/info/"+userId, function(r){
                vm.user = r.user;
                console.log("user:",r.user);
//                console.log(r.user);
//                console.log(vm.user);
//                vm.user.courseIdList = new Array(); 

//                var checkBoxValue = "" ;//已选课程的字符串
                vm.user.password = null;
                vm.getDept();
                
/*                $.ajax({
                    type: "POST",
                    url: baseURL + "jyxskc/findList",
                    datType: "JSON",
                    data: {
        				xh : vm.user.username ,
        				deleteState : "0"
        			},
                    success: function(r){
//                    	console.log("该学生的已选课程：");
//                    	console.log(r);
                    	for(var i = 0 ; i < r.list.length ; ++i){
                    		vm.user.courseIdList.push(r.list[i].kcid);
                    		checkBoxValue += r.list[i].kcid ;
                    		checkBoxValue += "," ;
                    	}
                    	
//                    	console.log(checkBoxValue);
                    	setTheCheckBoxValue(checkBoxValue);
                    }
                });*/
                
            });
        },
        getRoleList: function(){
            $.get(baseURL + "sys/role/select", function(r){
                vm.roleList = r.list;
//                console.log("vm.roleList:");
//                console.log(vm.roleList);
            });
        },
/*        getCourseList: function(){
            $.get(baseURL + "jykcxx/list", function(r){
                vm.courseList = r.page.list;
//                console.log(vm.courseList);
            });
        },*/
        deptTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['300px', '400px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级部门
                    vm.user.deptId = node[0].deptId;
                    vm.user.deptIdList.push(node[0].deptId);
                    vm.user.deptName = node[0].name;

                    layer.close(index);
                }
            });
        },
        reload: function () {
            vm.showList = true;
            vm.nameDisabled = false;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'username': vm.q.username},
                page:page
            }).trigger("reloadGrid");
        }
    }
});


/*function in_array(stringToSearch, arrayToSearch) {
    for (s = 0; s < arrayToSearch.length; s++) {
     thisEntry = arrayToSearch[s].toString();
     if (thisEntry == stringToSearch) {
      return true;
     }
    }
    return false;
}

function setTheCheckBoxValue( checkBoxValue ){
	var checkBoxArray = checkBoxValue.split(",");
	for(var i=0;i<checkBoxArray.length;i++){
		$("input[name='courseCheckBox']").each(function(){
			if($(this).val()==checkBoxArray[i]){
				//$(this).attr("checked","checked");
				$(this).click();
				//console.log("checked");
			}
		})
	}
}

function roleChange(that){
	var roleName = $(that).attr("valueName") ;
	
	if(roleName.indexOf("学生") != -1){//修改角色值包含学生关键字
		if($(that).is(':checked')){
			$("#courseDiv").show();
		}else{
			$("#courseDiv").hide();
		}
	}
}*/